﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IRM.Messaging.Test.Repository
{
    class InMemoryMessagesDataContext : InMemoryDataContext, IRM.Messaging.Repository.IMessagesDataContext
    {

        public IQueryable<Message> Messages
        {
            get { return GetEntities<Message>(); }
        }

        public void SaveStatus(Message message)
        {
            SubmitChanges();
        }
    }

    class InMemoryDataContext : IRM.Messaging.Repository.IDataContext
    {
        private List<object> inMemoryEntities = new List<object>();

        public IQueryable<T> GetEntities<T>()
            where T : class
        {
            var query = from objects in inMemoryEntities
                    where typeof (T).IsAssignableFrom(objects.GetType())
                    select objects;
 
            return query.Select(o => (T)o).AsQueryable();
        }

        public event EventHandler SavedChanges;

        protected void OnSaveChanges()
        {
            if (SavedChanges != null)
                SavedChanges(this, EventArgs.Empty);
        }

        public void Attach<T>(T entity, T original) where T : class
        {
            Remove<T>(original);
            Insert<T>(entity);
        }

        public void Insert<T>(T entity) where T : class
        {
            inMemoryEntities.Add(entity);
        }

        public void Remove<T>(T entity) where T : class
        {
            inMemoryEntities.Remove(entity);
        }

        public void SubmitChanges()
        {
            OnSaveChanges();
        }

        #region IDisposable Members

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}
